import 'dart:async';

import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:ls_work/widgets/select_item_widget.dart';

typedef ItemBuilder<T> = Widget Function(T item, bool hasSelected);
typedef OnSelectListener<T> = Function(List<T> selectItems);

Timer? _chooseTimer;
class SelectTagWidget<T> extends StatelessWidget {
  List<T> items;
  List<T>? selectedItems = [];
  ItemBuilder<T> builder;
  OnSelectListener<T>? onSelectListener;

  SelectTagWidget({required this.items,required this.builder,this.onSelectListener,this.selectedItems}){
    if(selectedItems==null){
      selectedItems = [];
    }
  }

  // Timer timer ;

  @override
  Widget build(BuildContext context) {
    return StatefulBuilder(builder: (context, setState) {
      return Wrap(
        spacing: 10,
        runSpacing: 10,
        children:
            items.map((e) => builder(e, selectedItems!.contains(e)).onTap(() {
                  setState(() {
                    if(selectedItems!.contains(e)){
                      selectedItems!.remove(e);
                    }else{
                      selectedItems!.add(e);
                    }

                    if(_chooseTimer!=null){
                      _chooseTimer!.cancel();
                    }

                    _chooseTimer =  Timer(Duration(seconds: 1), () {
                      if(onSelectListener!=null){
                        onSelectListener!(selectedItems!);
                      }
                    });
                  });
                })).toList(),
      );
    });
  }
}
